<template>
  <div class="news-management-page">
    <div class="page-header">
      <h1 class="page-title">新闻管理</h1>
      <a-button type="primary" @click="createNews">
        <template #icon><plus-outlined /></template>
        发布新闻
      </a-button>
    </div>
    
    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <a-form layout="inline" :model="filterForm">
        <a-form-item label="分类">
          <a-select
            v-model:value="filterForm.category"
            style="width: 120px"
            @change="handleFilterChange"
            :loading="categoriesLoading"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option 
              v-for="category in categories" 
              :key="category.id" 
              :value="category.id"
            >
              {{ category.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="filterForm.status"
            style="width: 120px"
            @change="handleFilterChange"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="published">已发布</a-select-option>
            <a-select-option value="draft">草稿</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-input-search
            v-model:value="filterForm.keyword"
            placeholder="搜索标题"
            style="width: 250px"
            @search="handleSearch"
          />
        </a-form-item>
      </a-form>
    </div>
    
    <!-- 新闻列表 -->
    <div class="news-table-container">
      <a-table
        :columns="columns"
        :data-source="newsList"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'title'">
            <div class="news-title-cell">
              <div class="news-title-text">{{ record.title }}</div>
              <div v-if="record.hasImage" class="news-has-image">[图]</div>
              <div v-if="record.hasVideo" class="news-has-video">[视]</div>
            </div>
          </template>
          <template v-else-if="column.key === 'category'">
            <a-tag :color="getCategoryColor(record.categoryId)">
              {{ getCategoryName(record.categoryId) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 'published' ? 'green' : 'orange'">
              {{ record.status === 'published' ? '已发布' : '草稿' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'publishTime'">
            {{ formatDate(record.publishTime) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="editNews(record.id)">
                <template #icon><edit-outlined /></template>
                编辑
              </a-button>
              <a-button type="link" size="small" @click="viewNews(record.id)">
                <template #icon><eye-outlined /></template>
                查看
              </a-button>
              <a-popconfirm
                title="确定要删除这条新闻吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="deleteNews(record.id)"
              >
                <a-button type="link" danger size="small">
                  <template #icon><delete-outlined /></template>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  EditOutlined,
  EyeOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import request from '../../utils/request' // 导入请求工具

const router = useRouter()
const loading = ref(false)
const categoriesLoading = ref(false)

// 分类数据
const categories = ref([])

// 筛选表单
const filterForm = reactive({
  category: '',
  status: '',
  keyword: ''
})

// 新闻列表数据
const newsList = ref([])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 表格列定义
const columns = [
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
    ellipsis: true,
    width: '30%'
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    width: '10%'
  },
  {
    title: '作者',
    dataIndex: 'author',
    key: 'author',
    width: '10%'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: '10%'
  },
  {
    title: '发布时间',
    dataIndex: 'publishTime',
    key: 'publishTime',
    width: '15%',
    sorter: true
  },
  {
    title: '浏览量',
    dataIndex: 'viewCount',
    key: 'viewCount',
    width: '10%',
    sorter: true
  },
  {
    title: '操作',
    key: 'action',
    width: '15%'
  }
]

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '-'
}

// 获取分类名称（更新为动态获取）
const getCategoryName = (categoryId) => {
  const category = categories.value.find(cat => cat.id === categoryId)
  return category ? category.name : '未分类'
}

// 获取分类颜色（保持原有逻辑，但可以考虑从后端获取）
const getCategoryColor = (categoryId) => {
  // 可以根据分类ID或名称设置颜色，这里保持简单的映射
  const colorMap = {
    1: 'blue',    // 假设ID为1的是学校要闻
    2: 'green',   // 假设ID为2的是学术动态
    3: 'purple',  // 假设ID为3的是综合新闻
    4: 'orange'   // 假设ID为4的是通知公告
  }
  return colorMap[categoryId] || 'default'
}

// 获取新闻列表
const fetchNewsList = async () => {
  loading.value = true
  try {
    // 实际项目中应该调用API
    const response = await request.post('/news/pageList/' + pagination.current + '/' + pagination.pageSize, {
        categoryId: filterForm.category,
        status: filterForm.status,
        title: filterForm.keyword,
      })

    if (response.code === 200) {
      newsList.value = response.data.records
      pagination.total = response.data.total
      // 分页
      const start = (pagination.current - 1) * pagination.pageSize
      const end = start + pagination.pageSize
    } else {
      message.error('获取新闻列表失败')
    }

    
    
    // // 模拟数据
    // await new Promise(resolve => setTimeout(resolve, 500))
    
    // // 生成模拟数据
    // const mockData = []
    // const categories = ['important', 'academic', 'general', 'notice']
    // const statuses = ['published', 'draft']
    
    // for (let i = 1; i <= 35; i++) {
    //   const category = categories[Math.floor(Math.random() * categories.length)]
    //   const status = statuses[Math.floor(Math.random() * statuses.length)]
    //   const date = new Date()
    //   date.setDate(date.getDate() - Math.floor(Math.random() * 30))
      
    //   // 应用筛选条件
    //   if ((filterForm.category && filterForm.category !== category) ||
    //       (filterForm.status && filterForm.status !== status) ||
    //       (filterForm.keyword && !`新闻标题示例 ${i}`.includes(filterForm.keyword))) {
    //     continue
    //   }
      
    //   mockData.push({
    //     id: i,
    //     title: `新闻标题示例 ${i}`,
    //     category,
    //     author: '新闻中心',
    //     status,
    //     publishTime: status === 'published' ? date.toISOString() : null,
    //     viewCount: status === 'published' ? Math.floor(Math.random() * 1000) + 100 : 0,
    //     hasImage: Math.random() > 0.5,
    //     hasVideo: Math.random() > 0.8
    //   })
    // }
    
    
    
  } catch (error) {
    message.error('获取新闻列表失败，请稍后再试')
    console.error('获取新闻列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理筛选条件变化
const handleFilterChange = () => {
  pagination.current = 1
  fetchNewsList()
}

// 处理搜索
const handleSearch = () => {
  pagination.current = 1
  fetchNewsList()
}

// 处理表格变化（分页、排序等）
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchNewsList()
}

// 创建新闻
const createNews = () => {
  router.push('/admin/news/create')
}

// 编辑新闻
const editNews = (id) => {
  router.push(`/admin/news/edit/${id}`)
}

// 查看新闻
const viewNews = (id) => {
  router.push(`/news/${id}`)
}

// 获取分类列表
const fetchCategories = async () => {
  categoriesLoading.value = true
  try {
    const response = await request.get('/categories/list')
    if (response.code === 200) {
      categories.value = response.data
    } else {
      message.error('获取分类列表失败')
    }
  } catch (error) {
    message.error('获取分类列表失败，请稍后再试')
    console.error('获取分类列表失败:', error)
  } finally {
    categoriesLoading.value = false
  }
}

// 删除新闻
const deleteNews = async (id) => {
  try {
    // 实际项目中应该调用API
    await request.get(`/news/del/${id}`)
  
    
    message.success('删除成功')
    fetchNewsList()
  } catch (error) {
    message.error('删除失败，请稍后再试')
    console.error('删除失败:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories() // 先获取分类数据
  fetchNewsList()
})
</script>

<style scoped>
.news-management-page {
  padding: 0 24px 20px;
  max-width: 1400px; /* 增加最大宽度 */
  margin: 0 auto; /* 居中显示 */
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #003366;
  margin: 0;
}

.filter-section {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.news-table-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow-x: auto; /* 添加横向滚动支持 */
  min-width: 900px; /* 设置最小宽度，确保表格不会过度压缩 */
}

.news-title-cell {
  display: flex;
  align-items: center;
  gap: 5px;
}

.news-title-text {
  flex: 1;
}

.news-has-image, .news-has-video {
  font-size: 12px;
  padding: 0 4px;
  border-radius: 2px;
  color: #fff;
}

.news-has-image {
  background-color: #1890ff;
}

.news-has-video {
  background-color: #ff4d4f;
}

@media (max-width: 768px) {
  .filter-section :deep(.ant-form-item) {
    margin-bottom: 16px;
  }
}
</style>

